/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

/**
 *
 * @author rcrida
 */
@Entity
@NamedQueries( {
    @NamedQuery(name="findAllTaskStateMachines",
                query="SELECT t FROM TaskStateMachine t WHERE t.deleted = FALSE ORDER BY t.name"),
    @NamedQuery(name="findTaskStateMachineStates",
                query="SELECT DISTINCT o FROM State o, TaskStateMachine t, IN (t.transitions) r WHERE t = :taskStateMachine AND (r.sourceState = o OR r.destinationState = o)")
})
public class TaskStateMachine extends Node implements Serializable {
    private static final long serialVersionUID = 1L;

    @OneToMany(mappedBy = "taskStateMachine")
    private Collection<Transition> transitions = new ArrayList<Transition>();

    @ManyToMany
    private Collection<Role> interestedRoles = new ArrayList<Role>();

    public TaskStateMachine() {
    }

    public TaskStateMachine(Node parentNode, String name, String description) {
        super(parentNode, name, description);
    }

    public Collection<Transition> getTransitions() {
        return transitions;
    }

    public void setTransitions(Collection<Transition> transitions) {
        this.transitions = transitions;
    }

    public Collection<Role> getInterestedRoles() {
        return interestedRoles;
    }

/*    public void updateTransition(Transition transition) {
        for (Transition currentTransition: new ArrayList<Transition>(transitions)) {
            if (currentTransition.getId().equals(transition.getId())) {
                transitions.remove(currentTransition);
                transitions.add(transition);
                break;
            }
        }
    }*/

    public void addInterestedRole(Role role) {
        if (!interestedRoles.contains(role)) {
            interestedRoles.add(role);
            role.getInterestedStateMachines().add(this);
        }
    }

    public void clearInterestedRoles() {
        for (Role role: interestedRoles) {
            role.getInterestedStateMachines().remove(this);
        }
        interestedRoles.clear();
    }

    public Transition getStartTransition() {
        for (Transition transition: getTransitions()) {
            if (transition.getSourceState().getName().equals("Start State"))
                return transition;
        }
        return null;
    }

}
